package com.thread.threadfirst.studyThread1;

import java.util.concurrent.TimeUnit;

/**
 * 13、synchronized优化
 * 同步代码块中的代码越少同步效率越高
 * 比较m1和m2
 */
public class T5 {
    int count = 0;

    synchronized void m1() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //业务逻辑只有下面这句，这时不应该给整个方法加锁
        count++;

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void m2() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //采用细粒度的锁，可以使线程争用时间变短，效率提高
        synchronized (this) {
            count++;
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
